//
//  Product_Checkout3View.m
//  iFlower
//
//  Created by khanh nguyen on 7/26/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "Product_Checkout3View.h"
#import "Product_Checkout4View.h"
#import "Request.h"
#import "iFlowerAppDelegate.h"
#import "Address.h"
#import "Country.h"
#import "State.h"
#import "Payment.h"
#import "Order.h"
#import "MyAccountView.h"
#import "LoginView.h"

@implementation Product_Checkout3View
@synthesize name;
@synthesize surname;
@synthesize address;
@synthesize city;
@synthesize postcode;
@synthesize email;
@synthesize phone;

@synthesize lblAddressBook;
@synthesize lblState;
@synthesize lblCountry;
@synthesize btnRegister;
//--------------------
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
	[name resignFirstResponder];
	[surname resignFirstResponder];
	[address resignFirstResponder];
	[city resignFirstResponder];
	[postcode resignFirstResponder];
	[email resignFirstResponder];
	[phone resignFirstResponder];
	[super touchesBegan:touches withEvent:event];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
	[UIView beginAnimations:nil context:NULL];
	self.view.frame = CGRectMake(self.view.frame.origin.x, 
								 self.view.frame.origin.y - 180, 
								 self.view.frame.size.width,
								 self.view.frame.size.height);
	[UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
	[UIView beginAnimations:nil context:NULL];
	self.view.frame = CGRectMake(self.view.frame.origin.x, 
								 self.view.frame.origin.y + 180, 
								 self.view.frame.size.width,
								 self.view.frame.size.height);
	[UIView commitAnimations];
}

//----------------------------------
-(IBAction)buttonBack:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)button_Next:(id)sender
{
	[[[iFlowerAppDelegate shareDelegate] payment] setShipAddress:currentAddress];
	[[[iFlowerAppDelegate shareDelegate] order] setAddress:currentAddress];
	Product_Checkout4View * check4 = [[Product_Checkout4View alloc]initWithNibName:@"Product_Checkout4View" bundle:nil];
	[self.navigationController pushViewController:check4 animated:YES];
	[check4 release];
}
-(IBAction)buttonMenu:(id)sender
{
	[self.navigationController popToRootViewControllerAnimated:YES];
}
//--------------------
-(IBAction)buttonSelec_AddressBook:(id)sender
{
	P1 = TRUE;
	actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
	CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
	pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
	pickerView.showsSelectionIndicator = YES;
	pickerView.dataSource = self;
	pickerView.delegate = self;
	[actionSheet addSubview:pickerView];
	//---
	UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
	closeButton.momentary = YES; 
	closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
	closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
	closeButton.tintColor = [UIColor blackColor];
	[closeButton addTarget:self action:@selector(dismissActionSheet1:) forControlEvents:UIControlEventValueChanged];
	[actionSheet addSubview:closeButton];
	[closeButton release];
	
	[actionSheet showInView:self.view];
	
	[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
-(IBAction)buttonSelec_State:(id)sender
{
	P2 = TRUE;
	actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
	CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
	pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
	pickerView.showsSelectionIndicator = YES;
	pickerView.dataSource = self;
	pickerView.delegate = self;
	[actionSheet addSubview:pickerView];
	//---
	UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
	closeButton.momentary = YES; 
	closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
	closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
	closeButton.tintColor = [UIColor blackColor];
	[closeButton addTarget:self action:@selector(dismissActionSheet2:) forControlEvents:UIControlEventValueChanged];
	[actionSheet addSubview:closeButton];
	[closeButton release];
	
	[actionSheet showInView:self.view];
	
	[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
-(IBAction)buttonSelec_Country:(id)sender
{
	P3 = TRUE;
	actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
	CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
	pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
	pickerView.showsSelectionIndicator = YES;
	pickerView.dataSource = self;
	pickerView.delegate = self;
	[actionSheet addSubview:pickerView];
	//---
	UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
	closeButton.momentary = YES; 
	closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
	closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
	closeButton.tintColor = [UIColor blackColor];
	[closeButton addTarget:self action:@selector(dismissActionSheet3:) forControlEvents:UIControlEventValueChanged];
	[actionSheet addSubview:closeButton];
	[closeButton release];
	
	[actionSheet showInView:self.view];
	
	[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
- (void) updateScreen
{
	if (currentAddress!=nil) {
		self.name.text = currentAddress.firstName;
		self.surname.text = currentAddress.lastName;
		self.postcode.text = currentAddress.zipCode;
		self.phone.text = currentAddress.phone;
		self.city.text = currentAddress.city;
		self.lblState.text = currentAddress.state;
		self.lblCountry.text = currentAddress.country;
		self.address.text = currentAddress.addressLine1;
	}
}
-(void)dismissActionSheet1:(id)sender
{
	[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
	currentAddress = [arrayAddres objectAtIndex:[pickerView selectedRowInComponent:0]];
	self.lblAddressBook.text = [currentAddress label];
	[self updateScreen];
	P1 = FALSE;
}

-(void)dismissActionSheet2:(id)sender
{
	[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
	self.lblState.text = [[arrayState objectAtIndex:[pickerView selectedRowInComponent:0]] state];	
	P2 = FALSE;
}
-(void)dismissActionSheet3:(id)sender
{
	[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
	self.lblCountry.text = [[arrayCountry objectAtIndex:[pickerView selectedRowInComponent:0]] countryName];	
	P3 = FALSE;
}

-(IBAction) buttonMyAccount
{
	if ([[iFlowerAppDelegate shareDelegate] logined]) {
		MyAccountView * account = [[MyAccountView alloc] initWithNibName:@"MyAccountView" bundle:nil];
		[self.navigationController pushViewController:account animated:YES];
		[account release];
	}
	else {
		LoginView * login = [[LoginView alloc] initWithNibName:@"LoginView" bundle:nil];
		[self.navigationController pushViewController:login animated:YES];
		[login release];		
	}
	
}

- (void) contentLoaded:(NSNotification*) notification
{
	NSLog(@"content loaded");
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	arrayAddres = [[NSMutableArray alloc] initWithCapacity:[[[[Request sharedRequest] entries] objectAtIndex:0]count]];
	arrayState = [[NSMutableArray alloc] initWithCapacity:[[[[Request sharedRequest] entries] objectAtIndex:2]count]];
	arrayCountry = [[NSMutableArray alloc] initWithCapacity:[[[[Request sharedRequest] entries] objectAtIndex:1]count]];
	for (NSDictionary* dictionary in [[[Request sharedRequest] entries] objectAtIndex:0])
	{
		Address* entry = [[Address new] autorelease];
		if (entry != nil)
		{
			entry.label = [dictionary objectForKey: @"label"];
			entry.firstName = [dictionary objectForKey: @"firstname"];
			entry.lastName = [dictionary objectForKey: @"lastname"];
			entry.addressLine1 = [dictionary objectForKey: @"address"];
			entry.addressLine2 = [dictionary objectForKey: @"address2"];
			entry.city = [dictionary objectForKey: @"city"];
			entry.state = [dictionary objectForKey: @"state"];
			entry.zipCode = [dictionary objectForKey: @"zipcode"];
			entry.country = [dictionary objectForKey: @"country"];
			entry.phone = [dictionary objectForKey: @"phone"];
			entry.fax = [dictionary objectForKey: @"fax"];
			entry.addressId = [dictionary objectForKey: @"id"];
			[arrayAddres addObject: entry];
		}
	}
	for (NSDictionary* dictionary in [[[Request sharedRequest] entries] objectAtIndex:1])
	{
		Country* entry = [[Country new] autorelease];
		if (entry != nil)
		{
			entry.categoryId = [[dictionary objectForKey: @"categoryid"] intValue];
			entry.countryName = [dictionary objectForKey: @"category"];
			[arrayCountry addObject: entry];
		}
	}
	for (NSDictionary* dictionary in [[[Request sharedRequest] entries] objectAtIndex:2])
	{
		State* entry = [[State new] autorelease];
		if (entry != nil)
		{
			entry.state = [dictionary objectForKey: @"state"];
			entry.stateId = [dictionary objectForKey: @"stateid"];
			entry.stateCode = [dictionary objectForKey: @"state_code"];
			entry.countryCode = [dictionary objectForKey: @"country_code"];
			[arrayState addObject: entry];
		}
	}
	[[iFlowerAppDelegate shareDelegate] hideLoadingView];
	
}
- (void) contentFailed:(NSNotification*) notification
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	NSLog(@"content failed");
	[[iFlowerAppDelegate shareDelegate] hideLoadingView];
}
#pragma mark -
#pragma mark View lifecycle
- (void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	if([[iFlowerAppDelegate shareDelegate] logined])
	{
		self.btnRegister.enabled = NO;
	}else {
		self.btnRegister.enabled = YES;
	}
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	//----
	P1 = FALSE;
	P2 = FALSE;
	P3 = FALSE;
    [[iFlowerAppDelegate shareDelegate] showLoadingView];
	
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentLoaded:) name: @"ContentLoaded" object: nil];
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentFailed:) name: @"ContentFailed" object: nil];
	
	[[Request sharedRequest] getAddressBooks:[[iFlowerAppDelegate shareDelegate] user]];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	self.lblAddressBook = nil;
	self.lblCountry = nil;
	self.lblState = nil;
}


- (void)dealloc {
	[lblAddressBook release];
	[lblCountry release];
	[lblState release];
	[name release];
	[surname release];
	[address release];
	[city release];
	[postcode release];
	[email release];
	[phone release];
    [super dealloc];
}
#pragma mark -
#pragma mark Picker View Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
	
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
	if(P1){
		return [arrayAddres count];
	}
	else if (P2){
		return [arrayState count];
	}
	else if (P3) {
		return [arrayCountry count];
	}
	return 0;
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	if (P1){
		return [[arrayAddres objectAtIndex:row] label];
	}
	else if (P2){
		return [[arrayState objectAtIndex:row] state];
	}
	else if (P3) {
		return [[arrayCountry objectAtIndex:row] countryName];
	}
	return nil;
}

//- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
	
//	NSLog(@"Selected Color: %@. Index of selected color: %i", [arrayColors objectAtIndex:row], row);
//}


@end
